package org.tao.lightningmq.nameserver.event.spi.listener;

import com.alibaba.fastjson2.JSON;
import org.tao.lightningmq.common.enums.NameServerEventCode;
import org.tao.lightningmq.common.event.Listener;
import org.tao.lightningmq.common.tcp.TcpMsg;
import org.tao.lightningmq.nameserver.common.CommonCache;
import org.tao.lightningmq.nameserver.event.model.ReplicationMsgEvent;
import org.tao.lightningmq.nameserver.event.model.SlaveReplicationMsgAckEvent;
import org.tao.lightningmq.nameserver.store.ServiceInstance;

/**
 * @Author lht
 * @date 2025/1/16 - 21:48
 * @description: 从节点使用的数据同步监听器
 */
public class ReplicationSlaveMsgListener implements Listener<ReplicationMsgEvent> {

    @Override
    public void onReceive(ReplicationMsgEvent event) throws Exception {
        ServiceInstance instance = event.getServiceInstance();
        CommonCache.getServiceInstanceManager().put(instance);
        SlaveReplicationMsgAckEvent slaveReplicationMsgAckEvent = new SlaveReplicationMsgAckEvent();
        slaveReplicationMsgAckEvent.setMsgId(event.getMsgId());
        slaveReplicationMsgAckEvent.setType(event.getType());
        event.getContext().channel().writeAndFlush(new TcpMsg(
                NameServerEventCode.SLAVE_REPLICATION_ACK_MSG.getCode(),
                JSON.toJSONBytes(slaveReplicationMsgAckEvent)
        ));
    }

}
